package com.aftersale.demo.utils;

import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 空
 * @date 2023/11/20 17:34
 * @desc
 */
public class MyUtil {
    public static Date getNow(){

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String now=sdf.format(new Date());
        Date date=null;
        try {
            date=sdf.parse(now);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
    //获取ip
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

    public static int getUserId(HttpServletRequest request){
        int userId=-1;
        String token = request.getHeader("token");
        if(StrUtil.isBlank(token)){
            userId=0;
        }
        else {
            try {
                Claims claims = JwtUtil.parseJwt(token);
                userId = Integer.parseInt(claims.getSubject());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return userId;
    }

}
